using System;

public class NetPacket : NetBuffer
{
    public const int HEADER_SIZE = 4;
    public const int MAX_NET_PACKET_SIZE = 65535;
    public const int MAX_BUFFER_SIZE = MAX_NET_PACKET_SIZE - HEADER_SIZE;

    public int Opcode { get; set; }

    public NetPacket(int opcode, int capacity = 256)
        : base(capacity)
    {
        Opcode = opcode;
    }

    public void ReadPacketHeader(out ushort opcode, out ushort size)
    {
        Read(out size);
        Read(out opcode);
        if (size < HEADER_SIZE)
        {
            throw new ArgumentOutOfRangeException();
        }
    }

    public void WritePacketHeader(int opcode, int size)
    {
        if (size > MAX_NET_PACKET_SIZE)
        {
            throw new ArgumentOutOfRangeException();
        }
        Write((ushort)size);
        Write((ushort)opcode);
    }

    public void ReadPacket(out NetPacket packet)
    {
        ReadPacketHeader(out ushort opcode, out ushort size);
        packet = new NetPacket(opcode, size - HEADER_SIZE);
        packet.Erlarge(size - HEADER_SIZE);
        Take(packet.GetBuffer(), 0, packet.GetSize());
    }

    public void WritePacket(NetPacket packet)
    {
        var size = packet.GetReadableSize();
        WritePacketHeader(packet.Opcode, HEADER_SIZE + size);
        Append(packet.GetBuffer(), packet.GetPosition(), size);
    }
}
